package com.woollen.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woollen.mapper.MemberMapper;
import com.woollen.model.Member;
import com.woollen.service.MemberService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    @Override
    public Integer register(Member member) {
        // 1. 校验手机号/邮箱唯一性
        QueryWrapper<Member> query = new QueryWrapper<>();
        if (member.getPhone() != null && !member.getPhone().isEmpty()) {
            query.eq("phone", member.getPhone());
        }
        if (member.getEmail() != null && !member.getEmail().isEmpty()) {
            query.eq("email", member.getEmail());
        }
        if (this.count(query) > 0) {
            throw new RuntimeException("手机号或邮箱已被注册");
        }
        // 2. 密码加密（MD5）
        String rawPwd = member.getPassword();
        String md5Pwd = DigestUtils.md5DigestAsHex(rawPwd.getBytes());
        member.setPassword(md5Pwd);
        // 3. 保留原有注册逻辑
        this.save(member);
        return member.getMbid();
    }

    @Override
    public Member login(String phoneOrEmail, String password) {
        // 支持手机号或邮箱登录，密码需加密比对
        String md5Pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        return this.lambdaQuery()
                .and(q -> q.eq(Member::getPhone, phoneOrEmail).or().eq(Member::getEmail, phoneOrEmail))
                .eq(Member::getPassword, md5Pwd)
                .one();
    }

    @Override
    public Member adminLogin(String username, String password) {
        String md5Pwd = org.springframework.util.DigestUtils.md5DigestAsHex(password.getBytes());
        Member member = this.lambdaQuery()
            .and(q -> q.eq(Member::getPhone, username).or().eq(Member::getEmail, username))
            .eq(Member::getPassword, md5Pwd)
            .eq(Member::getRole, "管理员")
            .one();
        if (member == null) {
            throw new RuntimeException("账号或密码错误，或无后台权限");
        }
        member.setPassword(null);
        return member;
    }
} 